const { Router } = require("express");
const JWT = require("jsonwebtoken");

const User = require("../model/User");

const router = new Router();
const map = {};

router.post("/send_code", (req, res) => {
    const tel = req.fetchBody.tel;
    let code = Math.floor(Math.random() * 100000);
    while (code.toString().length < 6) {
        code = "0" + code;
    }
    map[tel] = code.toString();
    console.log(code);
    setTimeout(() => {
        res.json({ code: 0, message: "ok" });
    }, 2000);
});
router.post("/check_code", async (req, res) => {
    const { tel, code } = req.fetchBody;
    console.log(tel,code);
    if (map[tel] !== code) {
        delete map[tel];
        res.json({ code: 1, message: "验证失败" });
        return;
    }
    // 做静默处理
    let user = await User.findOne({ tel });
    if (!user) {
        user = new User({ tel }).save();
    }

    //验证成功，可以登陆

    const token = JWT.sign(
        {
            tel,
            _id: user._id,
        },
        "hello world",
        {
            expiresIn: "7d",
        }
    );
    setTimeout(() => {
        res.json({ code: 0, message: "ok", data: token });
    }, 2000);
});

// 检查是否过期

router.get('/check_login',async(req,res)=>{
    try {
            const token=req.headers['authorization'].replace('Bearer',' ')
            const result=JWT.verify(token,'hello world');
            const user=await User.findById(result._id);
            if(user){
                res.json({code:0,message:'ok'})
            }
            else{
                throw new Error('用户不存在');
            }
    } catch (error) {
        res.json({code: -1, message: '请重新登录'});
    }
})


module.exports = router;
